package com.dongdongshop.serviceimpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.TbOrderService;
import com.dongdongshop.vo.OutTradeNoAndOItemVO;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@com.alibaba.dubbo.config.annotation.Service
public class TbOrderServiceImpl implements TbOrderService {
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    @Override
    public void insert(TbOrder tbOrder1) {
        tbOrderMapper.insertSelective(tbOrder1);
    }

    //增加流水号
    @Override
    public void update(TbOrder tbOrder) {
        TbOrderExample toe = new TbOrderExample();
        TbOrderExample.Criteria criteria = toe.createCriteria();
        criteria.andOutTradeNoEqualTo(tbOrder.getOutTradeNo());
        tbOrderMapper.updateByExampleSelective(tbOrder,toe);
    }

    //查询用户所有已支付商品
    @Override
    public List<OutTradeNoAndOItemVO> selectOrderStatus(TbUser tbUser) {
        //查询登录用户所有订单号
        List<String> outTradeNoList = tbOrderMapper.selectOrderStatus(tbUser.getUsername());

        List<OutTradeNoAndOItemVO> voList = new ArrayList<>();
        //遍历订单号查询购买的商品信息
        for (String s : outTradeNoList) {
            //将订单号以及订单号对应当商品放入vo类
            OutTradeNoAndOItemVO vo = new OutTradeNoAndOItemVO();
            vo.setOutTradeNo(s);
            TbOrderItemExample toe = new TbOrderItemExample();
            TbOrderItemExample.Criteria criteria1 = toe.createCriteria();
            criteria1.andOutTradeNoEqualTo(s);
            List<TbOrderItem> tbOrderItems = tbOrderItemMapper.selectByExample(toe);
            vo.setOrderItemList(tbOrderItems);
            //最后将vo类放入集合
            voList.add(vo);
        }
        return voList;
    }


    //删除商家订单信息
    @Override
    public void deleteByOutTradeNo(Long orderId) {
        TbOrderExample te = new TbOrderExample();
        TbOrderExample.Criteria criteria = te.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        tbOrderMapper.deleteByExample(te);
    }

    //根据订单获取用户id
    @Override
    public String selectUserId(String out_trade_no) {
        TbOrderExample te = new TbOrderExample();
        TbOrderExample.Criteria criteria = te.createCriteria();
        criteria.andOutTradeNoEqualTo(out_trade_no);
        List<TbOrder> tbOrders = tbOrderMapper.selectByExample(te);
        return tbOrders.get(0).getUserId();
    }

}
